package org.dizena.modules.master.dao;

import org.dizena.base.avo.req.JqGridReq;
import org.dizena.base.dao.BaseDao;
import org.dizena.base.dao.DbDao;
import org.dizena.modules.master.bean.Role;
import org.dizena.utils.ObjectUtil;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Repository
public class RoleDao extends BaseDao implements DbDao<Role>
{

    @Resource
    private MongoTemplate dao;

    @Override
    public Role add(Role m)
    {
        return dao.save(m);
    }

    @Override
    public void deleteById(String id)
    {
        dao.remove(idQuery(id), Role.class);
    }

    @Override
    public void deleteBy(String[] keys, Object[] vals)
    {
        Query query = keyIsVal(keys, vals);
        dao.remove(query, Role.class);
    }

    @Override
    public void update(Role m)
    {
        try
        {
            Update update = new Update();

            Map<String, Object> map = ObjectUtil.formObjectToMap(m);
            for (Map.Entry<String, Object> e : map.entrySet())
            {
                update.set(e.getKey(), e.getValue());
            }
            if (m.getRessIds() != null && m.getRessIds().size() > 0)
            {
                update.set("ressIds", m.getRessIds());
            }
            dao.updateFirst(idQuery(m.getId()), update, Role.class);
        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    @Override
    public Role get(String id)
    {
        return dao.findOne(idQuery(id), Role.class);
    }

    @Override
    public List<Role> findMany(String[] keys, Object[] vals)
    {
        Query query = keyIsVal(keys, vals);
        return dao.find(query, Role.class);
    }

    @Override
    public Long count(String[] keys, Object[] vals)
    {
        Query query = keyIsVal(keys, vals);
        return dao.count(query, Role.class);
    }

    @Override
    public List<Role> find(Long page, Integer size, String[] keys, Object[] vals)
    {
        Query query = keyIsVal(keys, vals);
        if (page != null && size != null)
        {
            query.skip((page - 1) * size);
            query.limit(size);
        }
        return dao.find(query, Role.class);
    }

    @Override
    public List<Role> queryAll(JqGridReq req, Map<String, Object> map)
    {

        return dao.find(allQuery(req, map), Role.class);
    }

    @Override
    public Long count(String searchField, Map<String, Object> map)
    {
        Query query = map2QueryLike(map, searchField);
        return dao.count(query, Role.class);
    }

    public Role getByRole(String role)
    {
        Query query = keyIsVal("role", role);
        return dao.findOne(query, Role.class);
    }
}
